/**
 * @author DongPing
 * 2022/3/9 9:57
 *
 * 选择单据类型
 *
 * */
import {ICellInputProps} from "@/biz-components/claim-items/components-v2/cell-input";
import {useEffect, useState} from "react";
import {TreeSelect} from "antd";
import {xhrPostJson} from "@/services";


/*
* 选择框的数据结构
* */
interface ITreeNodeData {
	label: string,
	value: string,
	children: ITreeNodeData[],
	disabled: boolean
}

export function SelectInvoiceType(props: ICellInputProps<string>) {
	const [data, setData] = useState<ITreeNodeData[]>([]);
	useEffect(function () {
		queryInvoiceTypes().then(setData);
	}, []);
	const {value, onChange} = props;
	return (
		<TreeSelect
			style={{ width: '100%' }}
			value={value}
			dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
			treeData={data}
			treeDefaultExpandAll
			onChange={(v) => {
				onChange(v);
			}}
			showSearch
			treeNodeFilterProp={"label"}
			allowClear
		/>
	)
}
SelectInvoiceType.defaultValue = '';

function queryInvoiceTypes(): Promise<ITreeNodeData[]> {
	return xhrPostJson('/asm/formType/tree', {pageCode: 'BillTypeTree_L'})
		.then((res: any) => {
			return transferData(res.result || []);
		})
}

function transferData(response: any[]): ITreeNodeData[] {
	const result: ITreeNodeData[] = [];
	for(const item of response) {
		result.push({
			label: item.name,
			value: item.code,
			children: item.children ? transferData(item.children) : [],
			disabled: !item.isLeaf
		})
	}
	return result;
}

